package dao;

import factory.ConnectionFactory;
import modelo.Aluno;
import java.sql.*;

public class AlunoDAO {
    private Connection connection;
    String nome;
    int cpf;
    String email;
    String endereco;
    int matricula;

    public AlunoDAO(){
       this.connection = new ConnectionFactory().getConnection();
    }

    public void adiciona(Aluno aluno){
        String sql = "INSERT INTO academia.aluno(nome_aluno,cpf_aluno,email_aluno,endereco_aluno,matricula_aluno) VALUES(?,?,?,?,?)";
        try {
           PreparedStatement stmt = connection.prepareStatement(sql);
           stmt.setString(1, aluno.getNome());
           stmt.setString(2, aluno.getCpf());
           stmt.setString(3, aluno.getEmail());
           stmt.setString(4, aluno.getEndereco());
           stmt.setInt(5, aluno.getMatricula());
           stmt.execute();
           stmt.close();
        } catch (SQLException u) {
            throw new RuntimeException(u);
        }
    }
    
    public Aluno seleciona(String cpf){
        String sql = "SELECT * FROM academia.aluno WHERE cpf_aluno = ?";
        try {
        	PreparedStatement stmt = connection.prepareStatement(sql);
        	stmt.setString(1, cpf);
        	ResultSet rs = stmt.executeQuery(); 
        	rs.next();
        	Aluno aluno = new Aluno();
        	aluno.setNome(rs.getString("nome_aluno"));
        	aluno.setCpf(rs.getString("cpf_aluno"));
        	aluno.setEmail(rs.getString("email_aluno"));
        	aluno.setEndereco(rs.getString("endereco_aluno"));
        	aluno.setMatricula(rs.getInt("matricula_aluno"));
       		rs.close();
       		stmt.close();
       		return aluno;
        } catch (SQLException u) {
            throw new RuntimeException(u);
        }
    }
    
    public void altera(Aluno aluno)
    {
        String sql = "UPDATE academia.aluno SET nome_aluno=?,email_aluno=?,endereco_aluno=?,matricula_aluno=? WHERE cpf_aluno=?";
        try
        {
           PreparedStatement stmt = connection.prepareStatement(sql);
           stmt.setString(1, aluno.getNome());
           stmt.setString(2, aluno.getEmail());
           stmt.setString(3, aluno.getEndereco());
           stmt.setInt(4, aluno.getMatricula());
           stmt.setString(5, aluno.getCpf());
           stmt.execute();
           stmt.close();
        }
        catch (SQLException u)
        {
            throw new RuntimeException(u);
        }
    }
    
    public void excluir(String cpf)
    {
        String sql = "delete FROM academia.aluno WHERE cpf_aluno = ?";
        try
        {
        	PreparedStatement stmt = connection.prepareStatement(sql);
        	stmt.setString(1, cpf);
        	stmt.execute();
       		stmt.close();
        }
        catch (SQLException u) 
        {
            throw new RuntimeException(u);
        }
    }

}
